<template>
  <view class="container padding-bottom-80">
    <view style="margin-top: 120rpx;"></view>
    <!-- 使用通用导航栏组件替换原有导航栏 -->
    <!-- 修改导航栏，添加动态标题 -->
    <nav-bar :title="formData.id ? '编辑订单' : '新建订单'" />
    
    <uni-forms ref="form" :model="formData" :rules="rules">
      <uni-forms-item label="客户">
        <text class="user-name">{{ userName }}</text>
      </uni-forms-item>
      <uni-forms-item label="订单项目" name="items" required>
        <view class="service-items-container">
          <view 
            v-for="item in serviceItems" 
            :key="item.product_id"
            class="service-item"
            :class="{ selected: formData.items.includes(item.product_id) }"
            @click.stop="toggleServiceItem(item.product_id)"
          >
            <text>{{ item.name }}</text>
            <text class="price">¥{{ item.price }}</text>
            <uni-icons 
              :type="formData.items.includes(item.product_id) ? 'checkbox-filled' : 'checkbox'" 
              :color="formData.items.includes(item.product_id) ? '#4cd964' : '#999'" 
              size="20"
            />
          </view>
        </view>
      </uni-forms-item>
      
      <uni-forms-item label="总金额" name="total_amount" required>
        <text class="total-amount">¥{{ calculateTotal() }}</text>
      </uni-forms-item
      
      <!-- 添加卡包选择 -->
      <uni-forms-item label="支付卡包" name="card_package_id">
        <view class="card-packages-container">
          <view 
            v-for="card in cardPackages" 
            :key="card.package_id"
            class="card-package-item"
            :class="{ selected: formData.card_package_id === card.package_id }"
            @click="selectCardPackage(card)"
          >
            <text class="card-name">{{ card.name }}</text>
            <text class="card-balance">
              <text v-if="card.card_type == 'comprehensive' || card.card_type == 'default'">余额: ¥{{ card.remaining_amount }}</text>
              <text v-else-if="card.card_type == 'per_use'">剩余次数:{{ card.remaining_amount }} </text>
            </text>
            
            <uni-icons 
              :type="formData.card_package_id === card.package_id ? 'checkbox-filled' : 'checkbox'" 
              :color="formData.card_package_id === card.package_id ? '#4cd964' : '#999'" 
              size="20"
            />
          </view>
          <!-- 添加卡包按钮 -->
          <view 
            class="card-package-item add-card-btn"
            @click="navigateToBindCardPackage"
          >
            <uni-icons type="plusempty" size="24" color="#999"></uni-icons>
            <text class="add-card-text">添加卡包</text>
          </view>
        </view>
      </uni-forms-item>

      <uni-forms-item label="支付方式" name="payment_method" required>
        <uni-group>
          <view class="payment-methods">
            <view 
              v-for="method in filteredPaymentMethods" 
              :key="method.value"
              class="payment-method"
              :class="{ selected: formData.payment_method === method.value }"
              @click="formData.payment_method = method.value"
            >
              <text>{{ method.text }}</text>
              <uni-icons 
                :type="formData.payment_method === method.value ? 'checkbox-filled' : 'checkbox'" 
                :color="formData.payment_method === method.value ? '#4cd964' : '#999'" 
                size="20"
              />
            </view>
          </view>
        </uni-group>
      </uni-forms-item>

      <!-- 添加员工选择 -->
      <uni-forms-item label="服务人员" name="staff_id" required>
        <view class="staff-container">
          <view 
            v-for="staff in staffList" 
            :key="staff.user_id"
            class="staff-item"
            :class="{ selected: formData.staff_id === staff.user_id }"
            @click="selectStaff(staff)"
          >
            <text class="staff-name">{{ staff.name }}</text>
            <uni-icons 
              :type="formData.staff_id === staff.user_id ? 'checkbox-filled' : 'checkbox'" 
              :color="formData.staff_id === staff.user_id ? '#4cd964' : '#999'" 
              size="20"
            />
          </view>
        </view>
      </uni-forms-item>
           <!-- 添加折扣后实付金额显示 -->
      <uni-forms-item label="折扣后实付" name="discounted_amount">
        <text class="total-amount" v-if="formData.card_package_id && selectedCard?.card_type === 'per_use'">次卡无需支付</text>
        <text class="total-amount" v-else>¥{{ discountedAmount }}</text>
      </uni-forms-item>
      <uni-forms-item label="备注" name="remarks">
        <uni-easyinput 
          type="textarea" 
          v-model="formData.remarks" 
          placeholder="请输入订单备注"
        />
      </uni-forms-item>
      
      <button type="primary" @click="submitForm">提交订单</button>
    </uni-forms>
  </view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
import order from '@/utils/order.js'
import product from '@/utils/product.js'
import cardPackage from '@/utils/card_package.js'
import store from '@/utils/store.js'

export default {
  components: {
    NavBar
  },
  data() {
    return {
      userName: '', // 添加用户名字段
      storeId: '',
      userId: '',
      cardPackages: [], // 添加卡包列表初始化
      staffList: [], // 添加员工列表初始化
      formData: {
        store_id: '',
        customer_id: '',
        items: [],
        total_amount: 0,
        payment_method: '',
        remarks: '',
        card_package_id: '',
        staff_id: '',
      },
      rules: {
        customer_id: {
          rules: [{ required: true, errorMessage: '请选择客户' }]
        },
        items: {
          rules: [{ required: true, errorMessage: '请选择服务项目' }]
        },
        total_amount: {
          rules: [{ required: true, errorMessage: '请输入金额' }]
        },
        payment_method: {
          rules: [{ required: true, errorMessage: '请选择支付方式' }]
        },
        card_package_id: {
          rules: [{ required: true, errorMessage: '请选择支付卡包' }]
        },
        staff_id: {
          rules: [{ required: true, errorMessage: '请选择服务人员' }]
        }
      },
      serviceItems: [], // 初始化为空数组
      paymentMethods: [
        { value: 'cash', text: '现金' },
        { value: 'card', text: '会员卡' },
        { value: 'wechat', text: '微信支付' },
        { value: 'alipay', text: '支付宝' }
      ]
    };
  },
  async onLoad(options) {
    this.storeId = options.store_id;
    this.userId = options.user_id;
    this.userName = decodeURIComponent(options.user_name || '');
    this.formData.store_id = this.storeId;
    this.formData.customer_id = this.userId;
    
    try {
      const products = await product.getAll();
      this.serviceItems = products.map(item => ({
        product_id: item.product_id,
        name: item.name,
        price: item.price,
        text: `${item.name} (¥${item.price})`
      }));
    } catch (error) {
      console.error('获取商品列表失败:', error);
      uni.showToast({
        title: '获取服务项目失败',
        icon: 'none'
      });
    }
    
    try {
      // 获取卡包列表
      await this.refreshCardPackages();

      // 获取员工列表
      const staffResponse = await store.getStoreUsers(this.storeId, {
        'roles[]': ['staff','owner','manager'] // 修改为数组格式
      });
      this.staffList = staffResponse.list || []; // 修正数据结构访问
      
      console.log('卡包列表:', this.cardPackages);
      console.log('员工列表:', this.staffList);
    } catch (error) {
      console.error('获取数据失败:', error);
      uni.showToast({
        title: '获取数据失败',
        icon: 'none'
      });
    }
  },
  computed: {
    // 添加支付方式过滤计算属性
    filteredPaymentMethods() {
      const selectedCard = this.cardPackages.find(card => card.package_id === this.formData.card_package_id);
      
      if (!selectedCard) {
        return this.paymentMethods;
      }
      
      // 默认卡包显示所有支付方式
      if (selectedCard.card_type === 'default') {
        return this.paymentMethods;
      } else {
        // 非默认卡包只显示会员卡支付方式
        return this.paymentMethods.filter(method => method.value === 'card');
      }
    },
    discountedAmount() {
      const totalAmount = parseFloat(this.calculateTotal());
      const selectedCard = this.cardPackages.find(card => card.package_id === this.formData.card_package_id);
      
      if (!selectedCard) {
        return totalAmount.toFixed(2);
      }

      if (selectedCard.card_type === 'per_use') {
        // 检查次数是否足够
        if (selectedCard.remaining_amount < this.formData.items.length) {
          return `次数不足(剩余${selectedCard.remaining_amount}次)`;
        }
        return '0.00';
      }

      // 默认卡包和综合卡都计算折扣
      const discountRate = selectedCard.discount_rate || 1; // 默认不打折
      const discountedAmount = totalAmount * discountRate;
      
      // 检查余额是否足够（仅对综合卡）
      if (selectedCard.card_type === 'comprehensive' && selectedCard.remaining_amount < discountedAmount) {
        return `余额不足支付¥${discountedAmount}(剩余¥${selectedCard.remaining_amount})`;
      }
      
      return discountedAmount.toFixed(2);
    },
  },
  onShow() {
    this.refreshCardPackages();
  },
  methods: {
    async refreshCardPackages() {
      try {
        const cardPackagesResponse = await cardPackage.getList({
          user_id: this.userId,
          store_id: this.storeId
        });
        this.cardPackages = cardPackagesResponse || [];
      } catch (error) {
        console.error('刷新卡包列表失败:', error);
        uni.showToast({
          title: '刷新卡包列表失败',
          icon: 'none'
        });
      }
    },
    navigateToBindCardPackage() {
      uni.navigateTo({
        url: `/pages/user/bind_card_package?store_id=${this.storeId}&user_id=${this.userId}`
      });
    },
    navigateBack() {
      uni.navigateBack();
    },
    calculateTotal() {
      return this.serviceItems
        .filter(item => this.formData.items.includes(item.product_id))
        .reduce((total, item) => total + item.price, 0)
        .toFixed(2);
    },
    toggleServiceItem(itemValue) {
      // 创建items数组的副本以避免直接修改
      const items = [...this.formData.items];
      const index = items.indexOf(itemValue);
      
      if (index === -1) {
        items.push(itemValue);
      } else {
        items.splice(index, 1);
      }
      console.log('items:',itemValue, items);
      // 使用Vue.set或直接赋值确保响应式更新
      this.formData.items = items;
      this.formData.total_amount = this.calculateTotal();
    },
    selectCardPackage(card) {
      this.formData.card_package_id = card.package_id;
      // 如果选择了非默认卡包，自动设置支付方式为会员卡
      if (card.card_type !== 'default') {
        this.formData.payment_method = 'card';
      }
    },

    selectStaff(staff) {
      this.formData.staff_id = staff.user_id;
    },

    async submitForm() {
      try {
        await this.$refs.form.validate();
             // 检查客户ID和服务人员ID不能相同
        if (this.formData.customer_id === this.formData.staff_id) {
          uni.showToast({
            title: '客户和服务人员不能是同一人',
            icon: 'none'
          });
          return;
        }
        // 检查卡包余额/次数
        if (this.formData.card_package_id) {
          const selectedCard = this.cardPackages.find(card => card.package_id === this.formData.card_package_id);
          // 只对非默认卡包进行余额检查
          if (selectedCard && selectedCard.card_type !== 'default') {
            if (selectedCard.card_type === 'per_use' && selectedCard.remaining_amount < this.formData.items.length) {
              uni.showToast({
                title: '卡包次数不足',
                icon: 'none'
              });
              return;
            }
            
            const discountedAmount = parseFloat(this.discountedAmount);
            if (selectedCard.card_type !== 'per_use' && selectedCard.remaining_amount < discountedAmount) {
              uni.showToast({
                title: '卡包余额不足',
                icon: 'none'
              });
              return;
            }
          }
        }

        const orderData = {
          store_id: this.formData.store_id,
          customer_id: this.formData.customer_id,
          items: this.formData.items,
          total_amount: this.formData.total_amount,
          payment_method: this.formData.payment_method,
          card_package_id: this.formData.card_package_id,
          staff_id: this.formData.staff_id,
          remarks: this.formData.remarks
        };
        
        const createdOrder = await order.create(orderData);
        uni.showToast({
          title: '订单创建成功',
          icon: 'success'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (error) {
        console.error('订单创建失败:', error);
        uni.showToast({
          title: error.message || '订单创建失败',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style>
.container {
  padding: 0 30rpx;
  background-color: #f5f5f5;
}

/* 删除原有的nav-bar相关样式 */

uni-forms {
  margin: 0 -30rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;
}

/* 添加以下样式 */
.service-items-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.service-item {
  display: flex;
  align-items: center;
  padding: 15rpx 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  margin-right: 15rpx;
  margin-bottom: 15rpx;
  background-color: #fff;
}

.service-item.selected {
  background-color: #4cd964;
  border-color: #4cd964;
  color: white;
}

.service-item.selected .uni-icons {
  color: white;
  border: 1rpx solid white;
  border-radius: 50%;
}

.payment-methods {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin: 0 -10rpx;
}

.payment-method {
  display: flex;
  align-items: center;
  padding: 15rpx 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  margin-right: 15rpx;
  margin-bottom: 15rpx;
  background-color: #fff;
}

.payment-method.selected {
  background-color: #4cd964;
  border-color: #4cd964;
  color: white;
}

.payment-method.selected .uni-icons {
  color: white;
  border: 1rpx solid white;
  border-radius: 50%;
}

.price {
  margin: 0 15rpx;
  color: #666;
}

.service-item.selected .price {
  color: white;
}

.total-amount {
  font-size: 32rpx;
  color: #f76260;
  font-weight: bold;
}
.user-name {
  font-size: 28rpx;
  color: #333333;
  font-weight: bold;
}

.uni-icons {
  margin-left: 10rpx;
}

.card-packages-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  padding: 10rpx;
}

.card-package-item {
  display: flex;
  flex-direction: column;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  background-color: #fff;
}

.card-package-item.selected {
  background-color: #4cd964;
  border-color: #4cd964;
  color: white;
}

.card-name {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.card-balance {
  font-size: 24rpx;
  color: #666;
}

.card-package-item.selected .card-balance {
  color: white;
}

.card-type {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.card-package-item.selected .card-type {
  color: white;
}

.staff-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15rpx;
  padding: 10rpx;
}

.staff-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  background-color: #fff;
}

.staff-item.selected {
  background-color: #4cd964;
  border-color: #4cd964;
  color: white;
}

.staff-name {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.staff-role {
  font-size: 24rpx;
  color: #666;
}

.staff-item.selected .staff-role {
  color: white;
}
.add-card-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #ddd;
  background-color: #f9f9f9;
}

.add-card-text {
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #999;
  text-align: center; /* 添加文字居中 */
  width: 100%; /* 确保宽度填满容器 */
}
</style>